ASP.Net Validation - CompareValidator

CompareValidator can not be the most used verifier of the bunch, but it is still useful in some cases. It can compare two values, the value of the two controls for example the next example, I could be you, it'll show you a small example of how to use it.


Small number:<br />
<asp:TextBox runat="server" id="txtSmallNumber" /><br /><br />
Big number:<br />
<asp:TextBox runat="server" id="txtBigNumber" /><br />
<asp:CompareValidator runat="server" id="cmpNumbers" controltovalidate="txtSmallNumber" controltocompare="txtBigNumber" operator="LessThan" type="Integer" errormessage="The first number should be smaller than the second number!" /><br />

As you see, we use a validator to validate only two areas. It may seem a little overwhelming, but it's actually very simple, like with RequiredFieldValidator, we use the attribute to control control to control control. In addition, we specify a control to compare. Operator attribute specifies which method to compare when using. In this case, we use the semaphore operator because we want the first control for the lowest value. We set the type in the integer, because we want to compare the integers, the dates, the strings and other value types can be compared well.

Now, try running the website, and test the two new fields. Here is what happens if you don't fill out the form correctly: 

The CompareValidator in action

If you change the numbers, then you will see another good thing about ASP.Net Vedic and Clienty Scripting: Validation is done even when you exit the field. If you do not want this, you can turn off enabled client scripting with enabled client attributes. You can also compare a field with a constant value. To do this, remove the controltocompare attribute, and add the valuetocompare attribute.

However, as you can see, the content of the two text boxes is not checked before comparing it. For example, it would be possible to enter nothing, or enter a piece of text instead of a number. When using Comparison Viadetator, you should always consider this as you can with the RequiredFieldValidator with empty fields, and you can protect with examples such as text with incorrect values, for example a regular Express Validator, We'll show you how to use it a little later.

If the ClientWith validation is not working, the invalid form will be captured from our piece of code in the codebahind file, as shown with the necessary field vendor. this is important.